package com.example.moderndashboard.Adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.GranularRoundedCorners;
import com.example.moderndashboard.Domain.TrendSDomain;
import com.example.moderndashboard.R;

import java.util.ArrayList;

public class TrendsAdapter extends RecyclerView.Adapter<TrendsAdapter.Viewholder> {
    private final ArrayList<TrendSDomain> items;
    private final Context context;

    public TrendsAdapter(Context context, ArrayList<TrendSDomain> items) {
        this.context = context;
        this.items = items;
    }

    @NonNull
    @Override
    public Viewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View inflater = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.viewholder_trend_list, parent, false);
        return new Viewholder(inflater);
    }

    @Override
    public void onBindViewHolder(@NonNull Viewholder holder, int position) {
        TrendSDomain item = items.get(position);

        holder.title.setText(item.getTitle());
        holder.subtitle.setText(item.getSubtitle());

        // 获取 picAddress，并从中提取 drawable 资源 ID
        String picAddress = item.getPicAddress();
        int drawableResourceId = context.getResources().getIdentifier(
                picAddress,
                "drawable",
                context.getPackageName()
        );

        // 检查 drawableResourceId 是否有效
        if (drawableResourceId != 0) {
            Glide.with(context)
                    .load(drawableResourceId)
                    .transform(new GranularRoundedCorners(30, 30, 0, 0))
                    .into(holder.pic);
        } else {
            // 处理资源 ID 无效的情况，例如加载默认图片或隐藏 ImageView
            holder.pic.setImageResource(R.drawable.women2); // 替换为你的默认图片资源
        }
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public static class Viewholder extends RecyclerView.ViewHolder {
        final TextView title;
        final TextView subtitle;
        final ImageView pic;

        public Viewholder(@NonNull View itemView) {
            super(itemView);

            title = itemView.findViewById(R.id.titleTxt);
            subtitle = itemView.findViewById(R.id.subtitleTxt);
            pic = itemView.findViewById(R.id.pic);
        }
    }
}

